package com.bestcem.xm.deliver.grpc.client;

import com.bestcem.bp.grpc.v1.base.Code;
import com.bestcem.xm.award.grpc.v1.services.Award;
import com.bestcem.xm.award.grpc.v1.services.AwardServiceGrpc;
import com.bestcem.xm.award.grpc.v1.services.GetAwardRequest;
import com.bestcem.xm.award.grpc.v1.services.GetAwardResponse;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.deliver.grpc.client.dto.AwardDto;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class AwardGrpcClient {

    @GrpcClient(GrpcClientNames.DS_AWARD)
    private AwardServiceGrpc.AwardServiceBlockingStub stub;

    public AwardDto getAward(String id, boolean needWind) {
        GetAwardRequest.Builder builder = GetAwardRequest.newBuilder();
        builder.setId(id);
        builder.setNeedWin(needWind);
        try {
            GetAwardResponse response = stub.getAward(builder.buildPartial());
            if (Objects.isNull(response) || Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[deliver] AWARD getAward {} Error; ErrorMsg: {}", id, response);
                return null;
            }
            return toAwardDto(response.getAward());
        } catch (Exception e) {
            log.error("[deliver] AWARD getAward {} Error; ErrorMsg: {}", id, e.getMessage(), e);
            return null;
        }
    }

    private AwardDto toAwardDto(Award award) {
        if (award == null) {
            return null;
        }

        //todo 自己补
        AwardDto dto = new AwardDto();
        dto.setId(award.getId());
        dto.setName(award.getName());
        return dto;
    }
}
